package com.javaweb.dao.impl;

import com.javaweb.dao.ArticleDao;
import com.javaweb.model.Article;
import com.javaweb.model.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/10/9 9:51
 */

@Repository
public class ArticleDaoImpl implements ArticleDao  {

    @Autowired
    JdbcTemplate jdbcTemplate ;


    @Override
    public int insert(Article article) {
        // Assert.notNull(article)

        String sql = "INSERT INTO tb_article (user_id, title, content, status, " +
                "description, category_id, create_time, update_time)" +
                " VALUES (?,?,?,?,?,?,?,?)" ;
        Object [] args = new Object[]{
                article.getUserId(),
                article.getTitle(),
                article.getContent(),
                article.getStatus(),
                article.getDescription(),
                article.getCategoryId(),
                new java.sql.Date(article.getCreateTime().getTime()),
                new java.sql.Date(article.getUpdateTime().getTime())}                               ;
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int updateContent(Integer id, String newContent) {
        return 0;
    }

    @Override
    public int updateTitle(Integer id, String newTitle) {
        return 0;
    }

    @Override
    public int deleteById(Integer id) {
        return 0;
    }

    @Override
    public List<Article> selectByUserId(Integer userId) {
        String sql = "SELECT a.*, " +
                " t.id as tag_id, t.name as tag_name, t.create_time as tag_create_time, t.update_time as tag_update_time, " +
                " c.sup, c.opp " +
                " FROM tb_article a " +
                " LEFT JOIN tb_article_tag at ON a.id=at.article_id " +
                " LEFT JOIN tb_tag t ON t.id=at.tag_id " +
                " LEFT JOIN " +
                " ( SELECT article_id, " +
                " IFNULL(SUM(support), 0) AS sup, " +
                " IFNULL(SUM(oppose),0) AS opp " +
                " FROM tb_comment GROUP BY article_id) c " +
                " ON c.article_id=a.id " +
                " WHERE a.user_id = ?" ;

        return jdbcTemplate.query(sql, new Object[]{userId},
                rs -> {
            Map<Integer, Article> articleMap = new HashMap<>();
            while (rs.next()) {
                Integer articleId = rs.getInt("id");
                Article article = articleMap.get(articleId);
                if (ObjectUtils.isEmpty(article)) {
                    article = new Article();
                    article.setId(articleId);
                    article.setTitle(rs.getString("title"));
                    article.setContent(rs.getString("content"));
                    article.setCreateTime(rs.getDate("create_time"));
                    article.setUpdateTime(rs.getDate("update_time"));
                    article.setTags(new ArrayList<>());
                    articleMap.put(articleId, article);
                }

                Integer tagId = rs.getInt("tag_id");
                if (tagId != null) {
                    Tag tag = new Tag();
                    tag.setId(tagId);
                    tag.setName(rs.getString("tag_name"));
                    tag.setCreateTime(rs.getDate("tag_create_time"));
                    tag.setUpdateTime(rs.getDate("tag_update_time"));
                    article.getTags().add(tag);
                }
                article.setSupportCount(rs.getInt("sup")) ;
                article.setOpposeCount(rs.getInt("opp")) ;
            }
            return new ArrayList<>(articleMap.values());
        });
    }


    @Override
    public int selectId(Integer userId, String title, Date createTime) {
        return 0;
    }

    @Override
    public List<Article> selectByKeyword(String keyword) {
        String sql = "SELECT * FROM tb_article WHERE title LIKE ? OR content LIKE ?" ;
        return jdbcTemplate.query(sql,new Object[]{"%" + keyword + "%"},
                new RowMapper<Article>() {
                    @Override
                    public Article mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Article article = new Article();
                        article.setId(rs.getInt("id"));
                        article.setTitle(rs.getString("title"));
                        article.setContent(rs.getString("content"));
                        article.setStatus(rs.getInt("status")) ;
                        article.setDescription(rs.getString("description")) ;
                        article.setCategoryId(rs.getInt("category_id")) ;
                        article.setCreateTime(rs.getDate("create_time")) ;
                        article.setUpdateTime(rs.getDate("update_time")) ;
                        return article;

                    }
                });
    }

    @Override
    public int updateStatus(Integer id, Integer status) {
        String sql = "UPDATE tb_article SET status = ? WHERE id=?" ;
        return jdbcTemplate.update(sql, new Object[]{status, id});
    }
}
